import json
import logging

import requests
from flask import Blueprint, request, jsonify

from backend.config import config
from predict import PredictService
from recommend import recommend

# 创建蓝图
api_bp = Blueprint('api', __name__, url_prefix='/api')
logger = logging.getLogger(__name__)
model_service = PredictService()


@api_bp.route('/cities', methods=['GET'])
def get_cities():
    """获取可用城市列表"""
    cities = model_service.get_available_city_list()
    return jsonify(cities)


@api_bp.route('/attributes', methods=['GET'])
def get_attributes():
    """获取可用属性列表的API端点
    city_name (str): 返回该城市可用的属性
    """
    city_name = request.args.get('city_name')
    attributes = model_service.get_available_attributes(city_name)
    return jsonify(attributes)


@api_bp.route('/history', methods=['GET'])
def get_history_data():
    """获取历史趋势
    city_name (str): 城市
    attribute (str): 属性
    返回: 历史数据
    """
    city_name = request.args.get('city_name')
    attribute = request.args.get('attribute')
    history_data = model_service.get_history_data(city_name, attribute)
    return jsonify(history_data)


@api_bp.route('/predict', methods=['POST'])
def predict_trend():
    """预测趋势
    请求参数:
        city_name (str): 城市
        attribute (str): 目标属性
        steps (int, 可选): 预测步数
    """
    data = request.get_json()
    city_name = data.get('city_name')
    attribute = data.get('attribute')
    steps = data.get('steps', 12)

    result = model_service.predict_trend(city_name, attribute, steps)
    return jsonify(result)


# API端点扩展
@api_bp.route('/recommend', methods=['POST'])
def recommend_attributes():
    """新版推荐API"""
    data = request.get_json()
    result = recommend(data['city_name'], data['age'], data['gender'], data['target_date'])
    return jsonify(result)


@api_bp.route('/recommend_images', methods=['POST'])
def recommend_images():
    """图文转换推荐API

    请求参数:
        description (str): 文本描述

    返回:
        JSON响应，包含图片URL列表
    """
    data = request.get_json()
    prompt = data.get('prompt')
    n = data.get('n')

    url = "https://qianfan.baidubce.com/v2/images/generations"

    payload = json.dumps({
        "prompt": prompt,
        "model": "irag-1.0",
        "n": int(n)
    }, ensure_ascii=False)
    headers = {
        'Content-Type': 'application/json',
        'Authorization': config.BAIDU_API_KEY
    }

    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

    print(response.text)

    images = [i['url'] for i in response.json()['data']]

    return jsonify({
        'status': 'success',
        'data': {
            'images': images,
            'description': prompt
        }
    })
